using System.IO;
using SmartBoard.Core.Serialization;

namespace SmartBoard.Core.Data
{
    public abstract class BoardElementStreamManagerBase:IBoardElementStreamManager
    {
        #region Fields
        protected readonly ISerializationStrategyProvider _serializationStrategyProvider;
        protected readonly IBoardElementDataManager _dataManager;
        #endregion

        #region Ctor
        protected BoardElementStreamManagerBase(ISerializationStrategyProvider serializationStrategyProvider, IBoardElementDataManager dataManager)
        {
            _serializationStrategyProvider = serializationStrategyProvider;
            _dataManager = dataManager;
        }
        #endregion

        #region Implementation of IBoardElementStreamManager

        public virtual void WriteToDataStream(Stream stream)
        {
            var streamVersion = this.GetValidStreamVersion();
            stream.WriteByte(streamVersion);
            _serializationStrategyProvider.Strategy(streamVersion).Serialize(stream, _dataManager.GetData());
        }

        public virtual void ReadFromDataStream(Stream stream)
        {
            var streamVersion = (byte)stream.ReadByte();
            var data = _serializationStrategyProvider.Strategy(streamVersion).Deserialize(stream);
            this.CurrentStreamVersion = streamVersion;
            _dataManager.SetData(data as IBoardElementData);
        }

        public byte CurrentStreamVersion
        {
            get; private set;
        }
        #endregion

        #region Protected Methods
        protected virtual byte GetValidStreamVersion()
        {
            if (this.CurrentStreamVersion == 0)
                return this.DefaultStreamVersion;
            return this.CurrentStreamVersion;
        }
        #endregion

        #region Abstract methods
        public abstract byte DefaultStreamVersion{ get;}
        #endregion
    }
}